#!/usr/bin/bash
#before release
project_name=$1
type=$2

java_opts=`echo ${@:3}`

project_tmp_dir=/data/target/
log_dir=/data/logs/${project_name}
release_scripts_dir=/data/scripts

project_run_dir="/data/servers/${project_name}"

#java_opts set
#java_opts="-Xms1G -Xmx1G -Xmn512M -Dserver.max-http-header-size=65536"
echo "java_opts: ${java_opts}"

#ip set
ip=$(/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{printf $2}'|tr -d "addr:")

#echo
echo "sh  ${release_scripts_dir}/release.sh ${project_name} ${java_opts} ${type}"


#fgf set
str=$(printf "%-10s" "#")
fgf=${str// /#}

#log color set
Log(){
    case ${1} in
        green)
            echo -e "\e[1;32m${2}\e[0m"
            ;;
        red)
            echo -e "\e[1;31m${2}\e[0m"
            ;;
        *)
            echo -e "${1}"
    esac
}

CopyPj(){
    test -d ${project_run_dir} || mkdir -p ${project_run_dir} 
    cp -rf ${project_tmp_dir}/${project_name}.jar ${project_run_dir}
}


StartService(){
    Log green "${fgf} 开始启动服务 ${fgf}"
    #清空启动日志
    test -d ${log_dir} || mkdir -p ${log_dir}
    log_file=${log_dir}/log.log
    [ -f $log_file ] && mv ${log_file} ${log_dir}/$(date '+%Y-%m-%d-%H-%M').log
    test -d ${project_run_dir} || mkdir -p ${project_run_dir}
    cd ${project_run_dir}
    source /etc/profile
 
    Log "nohup java ${java_opts}  -jar ${project_name}.jar >/dev/null 2>&1 &"
    nohup java ${java_opts}  -jar ${project_name}.jar >/dev/null 2>&1 &
    # sleep 5
   
}


#stop service
StopService(){
    Log green "${fgf} 开始停止服务 ${fgf}"
    a=0
    pid=$(ps -ef | grep java | grep ${project_name}.jar | grep -v grep | awk '{print $2}')
    if [ -n "${pid}" ];then
        Log "${project_name} PID: ${pid} "
        kill ${pid}
        while [[ ${a} -lt 10 && ${pid} ]]; do
            pid=$(ps -ef | grep java | grep ${project_name}.jar | grep -v grep | awk '{print $2}')
            a=$(expr $a + 1)
            Log "服务正在停止中........"
            sleep 1
        done
    else
        Log green "${project_name} 服务没有运行,请检查......."
    fi
    if [[ ${a} = 10 && ${pid} ]];then
        Log red "服务停止失败,准备 kill -9 ${pid} 强制停止 "
        kill -9 ${pid}
    fi
    Log green "${fgf} 服务已停止运行 ${fgf}"
}


#release 
case ${type} in
    start)
        StopService
        CopyPj
        StartService
    ;;
    stop)
        StopService
    ;;
    *)
        Log  red "New function to be developed..."
        exit 1
    ;;  
esac
